// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package user

import (
	"audio-server/internal/model"
	"context"
	"database/sql"
	"encoding/json"
	"errors"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserLogic {
	return &UpdateUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateUserLogic) UpdateUser(req *types.UserUpdateReq) (resp bool, err error) {
	usersModel := model.NewUsersModel(l.svcCtx.Conn)
	user, err := usersModel.FindById(l.ctx, req.Id)
	if err != nil || errors.Is(err, sql.ErrNoRows) {
		return false, errors.New("用户不存在")
	}
	user.Username = req.Username
	user.Nickname = req.Nickname
	user.Avatar = req.Avatar
	user.Gender = int64(req.Gender)
	user.Description = sql.NullString{String: req.Description, Valid: true}

	jsonData, err := json.Marshal(req.RoleIds)
	user.RoleIds = string(jsonData)
	err = usersModel.Update(l.ctx, user)
	if err != nil {
		return false, err
	}
	return true, nil
}
